function hasChild (item) {
    return item.children && item.children.length !== 0;
};

export const getMenuByRouter = (routes) => {
    let res = [];

    routes.forEach(item => {
        if (item.meta) {
            let obj = {
                label: item.meta.title,
                name: item.name
            };
            if (hasChild(item)) {
                obj.children = getMenuByRouter(item.children);
            }
            res.push(obj);
        }
    });

    return res;
};

/**
 * @param {string} url
 * @returns {Object}
 */
export function getQueryObject (url) {
    url = url == null ? window.location.href : url;
    const search = url.substring(url.lastIndexOf('?') + 1);
    const obj = {};
    const reg = /([^?&=]+)=([^?&=]*)/g;
    search.replace(reg, (rs, $1, $2) => {
        const name = decodeURIComponent($1);
        let val = decodeURIComponent($2);
        val = String(val);
        obj[name] = val;
        return rs;
    });
    return obj;
}

/**
 * 树形数据转换
 * @param {*} data
 * @param {*} id
 * @param {*} pid
 */
export function treeDataTranslate (data, id = 'id', pid = 'parentId') {
    let res = [];
    let temp = {};
    for (let i = 0; i < data.length; i++) {
        temp[data[i][id]] = data[i];
    }
    for (let k = 0; k < data.length; k++) {
        if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
            if (!temp[data[k][pid]]['children']) {
                temp[data[k][pid]]['children'] = [];
            }
            if (!temp[data[k][pid]]['_level']) {
                temp[data[k][pid]]['_level'] = 1;
            }
            data[k]['_level'] = temp[data[k][pid]]._level + 1;
            temp[data[k][pid]]['children'].push(data[k]);
        } else {
            res.push(data[k]);
        }
    }
    return res;
}

/**
 *
 * @date 2018/4/9
 * @Description: 时间格式化 使用方式parseTime('{y}-{m}-{d} {h}:{i}:{s}')
 *
 */
export function parseTime (time, cFormat) {
    if (arguments.length === 0) {
        return null;
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
    let date;
    if (typeof time === 'object') {
        date = time;
    } else {
        if (('' + time).length === 10) { time = parseInt(time) * 1000; }
        date = new Date(time);
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    };
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key];
        if (key === 'a') { return ['一', '二', '三', '四', '五', '六', '日'][value - 1]; }
        if (result.length > 0 && value < 10) {
            value = '0' + value;
        }
        return value || 0;
    });
    return time_str;
}

/**
 * @author KdZhao/dongwenzhao@lngtop.com
 * @date 2019-01-04 14:10:27
 * @Description: 节流函数
 */
export function throttle (fn, interval) {
    var __self = fn; // 保存需要被延迟执行的函数引用
    var timer; // 定时器
    var firstTime = true; // 是否是第一次调用
    return function () {
        var args = arguments;
        var __me = this;
        if (firstTime) { // 如果是第一次调用，不需延迟执行
            __self.apply(__me, args);
            firstTime = false;
            return firstTime;
        }
        if (timer) { // 如果定时器还在，说明前一次延迟执行还没有完成
            return false;
        }
        timer = setTimeout(function () { // 延迟一段时间执行
            clearTimeout(timer);
            timer = null;
            __self.apply(__me, args);
        }, interval || 500);
    };
};
function convertTime (time) {
    const [amt, t = 'ms'] = String(time).split(/(ms|s)/i);
    const types = {
        ms: 1,
        s: 1000
    };

    return Number(amt) * types[t];
}

export function debounce (fn, wait) {
    let timeout = null;
    const timer = typeof wait === 'number' ? wait : convertTime(wait);

    const debounced = function (...args) {
        const later = () => {
            timeout = null;

            fn.apply(this, args);
        };

        clearTimeout(timeout);
        timeout = setTimeout(later, timer);

        if (!timeout) {
            fn.apply(this, args);
        }
    };

    debounced.cancel = () => {
        clearTimeout(timeout);
        timeout = null;
    };

    return debounced;
};

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj (url) {
    const search = url.split('?')[1];
    if (!search) {
        return {};
    }
    return JSON.parse(
        '{"' +
        decodeURIComponent(search)
            .replace(/"/g, '\\"')
            .replace(/&/g, '","')
            .replace(/=/g, '":"')
            .replace(/\+/g, ' ') +
        '"}'
    );
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone (source) {
    if (!source && typeof source !== 'object') {
        throw new Error('error arguments', 'deepClone');
    }
    const targetObj = source.constructor === Array ? [] : {};
    Object.keys(source).forEach(keys => {
        if (source[keys] && typeof source[keys] === 'object') {
            targetObj[keys] = deepClone(source[keys]);
        } else {
            targetObj[keys] = source[keys];
        }
    });
    return targetObj;
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass (ele, cls) {
    return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass (ele, cls) {
    if (!hasClass(ele, cls)) { ele.className += ' ' + cls; }
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass (ele, cls) {
    if (hasClass(ele, cls)) {
        const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
        ele.className = ele.className.replace(reg, ' ');
    }
}

export const filterTreeDisable = (data, disableArr) => {
    let res = [];
    data.forEach(item => {
        if (item) {
            let {children, ...obj} = item;
            if (disableArr && disableArr.length && disableArr.includes(obj.value)) {
                obj.disabled = true;
            }
            if (hasChild(item)) {
                obj.children = filterTreeDisable(item.children, disableArr);
            }
            res.push(obj);
        }
    });
    return res;
};

/**
 * 倒计时解析
 *
 *
 */

export function parseCountDownTimeData (time) {
    let SECOND = 1000;
    let MINUTE = 60 * SECOND;
    let HOUR = 60 * MINUTE;
    let DAY = 24 * HOUR;
    let days = Math.floor(time / DAY);
    let hours = Math.floor(time % DAY / HOUR);
    let minutes = Math.floor(time % HOUR / MINUTE);
    let seconds = Math.floor(time % MINUTE / SECOND);
    let milliseconds = Math.floor(time % SECOND);
    return {
        days: days,
        hours: hours,
        minutes: minutes,
        seconds: seconds,
        milliseconds: milliseconds
    };
}

// 加法精度
export function addPrice (arg1, arg2) {
    let r1, r2;
    try { r1 = arg1.toString().split('.')[1].length; } catch (e) { r1 = 0; }
    try { r2 = arg2.toString().split('.')[1].length; } catch (e) { r2 = 0; }
    const m = Math.pow(10, Math.max(r1, r2));
    return (arg1 * m + arg2 * m) / m;
}

// 减法函数精度
export function subPrice (arg1, arg2) {
    let r1, r2;
    try { r1 = arg1.toString().split('.')[1].length; } catch (e) { r1 = 0; }
    try { r2 = arg2.toString().split('.')[1].length; } catch (e) { r2 = 0; }
    const m = Math.pow(10, Math.max(r1, r2));
    const n = (r1 >= r2) ? r1 : r2;
    return Number(((arg1 * m - arg2 * m) / m).toFixed(n));
}
// 除法函数精度
export function divisionPrice (num1, num2) {
    let t1, t2;
    try {
        t1 = num1.toString().split('.')[1].length;
    } catch (e) {
        t1 = 0;
    }
    try {
        t2 = num2.toString().split('.')[1].length;
    } catch (e) {
        t2 = 0;
    }
    const r1 = Number(num1.toString().replace('.', ''));
    const r2 = Number(num2.toString().replace('.', ''));
    return (r1 / r2) * Math.pow(10, t2 - t1);
}

// 乘法函数精度
export function mclPrice (num1, num2) {
    let m = 0; const s1 = num1.toString(); const s2 = num2.toString();
    try { m += s1.split('.')[1].length; } catch (e) {}
    try { m += s2.split('.')[1].length; } catch (e) {}
    return Number(s1.replace('.', '')) * Number(s2.replace('.', '')) / Math.pow(10, m);
}
